//
//  YPHomePageDynamicVC.m
//  WHISPER
//
//  Created by lanou3g on 15/12/17.
//  Copyright © 2015年 王艳苹. All rights reserved.
//

#import "YPHomePageDynamicVC.h"
#import "YPNetWorking.h"
#import "YPMakeURL.h"
#import "YPDynamicModle.h"
#import "YPUser.h"
#import "YPCounterListModle.h"
#import "YPDynamicVCCell.h"
#import "UIImageView+WebCache.h"
#import "leftimageButton.h"
#import "MJRefresh.h"
#import "UIView+Extention.h"
#import "YPWebViewVC.h"
#import "YPLikeHelper.h"
#import "YPJudgeNet.h"
#import "YPDataBase.h"

static YPHomePageDynamicVC *dynamicVC = nil;
@interface YPHomePageDynamicVC ()

@property (nonatomic,strong) NSMutableArray *dynamicArray;
@property (nonatomic,assign) float cellH;
@property (nonatomic,assign) BOOL likeFlag;
@property (nonatomic,strong) YPLikeHelper *like;
@property (nonatomic,strong) YPDataBase *database;
@end

@implementation YPHomePageDynamicVC
static NSInteger flag = 0;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"YPDynamicVCCell" bundle:nil] forCellReuseIdentifier:@"YPDynamicVCCell"];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(upFreash)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(downFresh)];
    [self JudgeNet];
}
- (void)JudgeNet{
    if ([[YPJudgeNet shareJudgeNet] isConnection]) {
        [self getData];
    }else{
        [self.database getDynamicDataFromDataBaseSuccess:^(NSArray *arr) {
            self.dynamicArray = (NSMutableArray*)arr;
            [self.tableView reloadData];
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
        }];
    }
}
- (void)getData{
    [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].homePageDynamicHeaderURL dict:[YPMakeURL shareMakeURL].homePageParameterDynamicDic success:^(NSDictionary *dict) {
        self.dynamicArray = @[].mutableCopy;
        [self.database deleteDynamicSuccess:^{
        } fail:^(NSError *err) {
            NSLog(@"删除失败%@",err);
        }];
        [self.database insertDataWithDynamicDic:dict success:^{
        } fail:^(NSError *err) {
            NSLog(@"%@",err);
        }];
        for (NSDictionary *tempDic in dict[@"data"][@"list"]) {
            YPDynamicModle *modle = [[YPDynamicModle alloc]init];
            [modle setValuesForKeysWithDictionary:tempDic];
            modle.userinfo = [[YPUser alloc]init];
            [modle.userinfo setValuesForKeysWithDictionary:tempDic[@"userinfo"]];
            modle.counterList = [[YPCounterListModle alloc]init];
            [modle.counterList setValuesForKeysWithDictionary:tempDic[@"counterList"]];
            NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
            if (login == nil || [login isEqualToString:@"nlogin"]) {//初次安装程序，或者已经退出登陆
                //nothing
            }else{
                NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
                [self.like isLikeWith:modle.contentid name:name success:^(BOOL flag) {
                    if (flag) {
                        modle.counterList.like++;
                    }
                    modle.flag = flag;
                }];
            }
            modle.userinfos = @[].mutableCopy;
            for (NSDictionary *dic in tempDic[@"userinfos"]) {
                YPUser *user = [[YPUser alloc]init];
                [user setValuesForKeysWithDictionary:dic];
                [modle.userinfos addObject:user];
            }
            [self.dynamicArray addObject:modle];
        }
        [self.tableView reloadData];
    } fail:^(NSError *err) {
    }];
}
- (void)upFreash{
    if ([[YPJudgeNet shareJudgeNet] isConnection]) {
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].homePageDynamicHeaderURL dict:[YPMakeURL shareMakeURL].homePageParameterDynamicDic success:^(NSDictionary *dict) {
            [self.dynamicArray removeAllObjects];
            for (NSDictionary *tempDic in dict[@"data"][@"list"]) {
                YPDynamicModle *modle = [[YPDynamicModle alloc]init];
                [modle setValuesForKeysWithDictionary:tempDic];
                modle.userinfo = [[YPUser alloc]init];
                [modle.userinfo setValuesForKeysWithDictionary:tempDic[@"userinfo"]];
                modle.counterList = [[YPCounterListModle alloc]init];
                [modle.counterList setValuesForKeysWithDictionary:tempDic[@"counterList"]];
                NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
                if (login == nil || [login isEqualToString:@"nlogin"]) {//初次安装程序，或者已经退出登陆
                    //nothing
                }else{
                    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
                    [self.like isLikeWith:modle.contentid name:name success:^(BOOL flag) {
                        if (flag) {
                            modle.counterList.like++;
                        }
                        modle.flag = flag;
                    }];            }
                modle.userinfos = @[].mutableCopy;
                for (NSDictionary *dic in tempDic[@"userinfos"]) {
                    YPUser *user = [[YPUser alloc]init];
                    [user setValuesForKeysWithDictionary:dic];
                    [modle.userinfos addObject:user];
                }
                [self.dynamicArray addObject:modle];
            }
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
        } fail:^(NSError *err) {
        }];
    }else{
        [self alertController:@"请检查网络"];
        [self.tableView.mj_header endRefreshing];
    }
}
- (void)downFresh{
    if ([[YPJudgeNet shareJudgeNet] isConnection]) {
        flag += 10;
        [[YPNetWorking shareNetWorking] getDictWithURL:[YPMakeURL shareMakeURL].homePageDynamicHeaderURL dict:[[YPMakeURL shareMakeURL] makeDynamicDownFreashDicWithNum:flag] success:^(NSDictionary *dict) {
            for (NSDictionary *tempDic in dict[@"data"][@"list"]) {
                YPDynamicModle *modle = [[YPDynamicModle alloc]init];
                [modle setValuesForKeysWithDictionary:tempDic];
                modle.userinfo = [[YPUser alloc]init];
                [modle.userinfo setValuesForKeysWithDictionary:tempDic[@"userinfo"]];
                modle.counterList = [[YPCounterListModle alloc]init];
                [modle.counterList setValuesForKeysWithDictionary:tempDic[@"counterList"]];
                modle.userinfos = @[].mutableCopy;
                NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
                if (login == nil || [login isEqualToString:@"nlogin"]) {//初次安装程序，或者已经退出登陆
                    //nothing
                }else{
                    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
                    [self.like isLikeWith:modle.contentid name:name success:^(BOOL flag) {
                        if (flag) {
                            modle.counterList.like++;
                        }
                        modle.flag = flag;
                    }];
                }
                for (NSDictionary *dic in tempDic[@"userinfos"]) {
                    YPUser *user = [[YPUser alloc]init];
                    [user setValuesForKeysWithDictionary:dic];
                    [modle.userinfos addObject:user];
                }
                
                [self.dynamicArray addObject:modle];
            }
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        } fail:^(NSError *err) {
        }];
    }else{
        [self alertController:@"请检查网络"];
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dynamicArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YPDynamicVCCell *cell =  [tableView dequeueReusableCellWithIdentifier:@"YPDynamicVCCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YPDynamicModle *model = self.dynamicArray[indexPath.row];
    cell.userImage.layer.masksToBounds = YES;
    cell.userImage.layer.cornerRadius = 20;
    [cell.userImage sd_setImageWithURL:[NSURL URLWithString:model.userinfo.icon]];
    cell.userName.text = model.userinfo.uname;
    cell.timeLable.text = model.addtime_f;
    [cell.likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    if (model.counterList.like == 0) {
        cell.likeLable.text = nil;
    }else if(model.counterList.like >= 99){
        cell.likeLable.text = @"99+";
    }else{
      cell.likeLable.text = [NSString stringWithFormat:@"%ld",(long)model.counterList.like];
    }
        if (model.ctype == 24) {
            if (model.userinfos.count ==  1) {
                cell.typeLable.text = @"喜欢了一个话题";
            }else{
                cell.typeLable.text = [NSString stringWithFormat:@"等%ld喜欢了一个话题",(unsigned long)model.userinfos.count];
            }
        }
       if(model.ctype == 15){
            if (model.userinfos.count ==  1) {
                cell.typeLable.text = @"喜欢了一篇文章";
            }else{
                cell.typeLable.text = [NSString stringWithFormat:@"等%ld喜欢了一篇文章",(unsigned long)model.userinfos.count];
            }
        }
       if(model.ctype == 2){
            if (model.userinfos.count ==  1) {
                cell.typeLable.text = @"喜欢了一个碎片";
            }else{
                cell.typeLable.text = [NSString stringWithFormat:@"等%ld喜欢了一个碎片",(unsigned long)model.userinfos.count];
            }
       }
       if (model.ctype == 0) {
            cell.typeLable.text = @"发表了一个碎片";
        }
    if ([model.coverimg isEqualToString:@""]){
        cell.contentImage.frame = CGRectMake(0, 0, 0, 0);
        if ([model.content isEqualToString:@""]) {
            float contentH = [self stringHight:model.content width:cell.width - 40];
            cell.contentLable.frame = CGRectMake(20,CGRectGetMaxY(cell.typeLable.frame)+10,cell.width - 40,contentH);
            cell.contentLable.text = @"有人在唱歌";
            cell.contentLable.numberOfLines = 0;
            cell.contentLable.font = [UIFont systemFontOfSize:15];
            cell.contentLable.hight = contentH;
            self.cellH = contentH;
        }else{
            float contentH = [self stringHight:model.content width:cell.width - 40];
            cell.contentLable.frame = CGRectMake(20,CGRectGetMaxY(cell.typeLable.frame)+10,cell.width - 40,contentH);
            cell.contentLable.text = model.content;
            cell.contentLable.numberOfLines = 0;
            cell.contentLable.font = [UIFont systemFontOfSize:15];
            cell.contentLable.hight = contentH;
            self.cellH = contentH;
        }
    }else{
        NSArray *arr = [model.coverimg_wh componentsSeparatedByString:@"*"];
        float imageH = [arr[0] floatValue];
        float imageW = [arr[1] floatValue];
        cell.contentImage.frame = CGRectMake(20, CGRectGetMaxY(cell.typeLable.frame) + 10, cell.width - 40, (cell.width - 40) * (imageW / imageH));
        [cell.contentImage sd_setImageWithURL:[NSURL URLWithString:model.coverimg] placeholderImage:[UIImage imageNamed:@"16"]];
        self.cellH = (cell.width - 40) * (imageW / imageH);
        if ([model.content isEqualToString:@""]) {
            cell.contentLable = nil;
        }else{
            float contentH = [self stringHight:model.content width:cell.width - 40];
            cell.contentLable.frame = CGRectMake(20,CGRectGetMaxY(cell.contentImage.frame)+10,cell.width - 40,contentH);
            cell.contentLable.text = model.content;
            cell.contentLable.numberOfLines = 0;
            cell.contentLable.font = [UIFont systemFontOfSize:15];
            cell.contentLable.hight = contentH;
            self.cellH = (cell.width - 40) * (imageW / imageH) + contentH;
        }
    }
    cell.likeButton.tag = 250 + indexPath.row;
    [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
    if (model.flag) {
        [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:(UIControlStateNormal)];
    }
    
    return cell;
}

-(CGFloat)stringHight:(NSString*)str width:(CGFloat)width{
    CGRect temp = [str boundingRectWithSize:CGSizeMake(width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    return temp.size.height;
}
- (void)likeButtonAction:(UIButton*)sender{
    
    YPDynamicModle *model = self.dynamicArray[sender.tag - 250];
    //是否有用户登陆
    NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];
    NSString *name  = nil;
    if (login == nil || [login isEqualToString:@"nlogin"]) {//初次安装程序，或者已经退出登陆
        [self alertController:@"请先登录用户"];
        return;//直接退出
    }else{
        name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    }

    NSIndexPath *index = [NSIndexPath indexPathForRow:sender.tag-250 inSection:0];
    YPDynamicVCCell *cell = [self.tableView cellForRowAtIndexPath:index];
    model.flag = !model.flag;
    if (model.flag) {
        [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan"] forState:(UIControlStateNormal)];
        cell.likeLable.text = [NSString stringWithFormat:@"%ld",++model.counterList.like];
        [self alertController:@"谢谢喜欢"];
        [self.like addLikeWithUrl:model.contentid name:name];
    }else{
        [cell.likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan-2"] forState:(UIControlStateNormal)];
        cell.likeLable.text = [NSString stringWithFormat:@"%ld",--model.counterList.like];
        [self alertController:@"取消喜欢"];
        [self.like deleteLike:model.contentid name:name];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 145 + self.cellH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     YPDynamicModle *model = self.dynamicArray[indexPath.row];
    if ((model.ctype == 0 && model.type == 17) || (model.ctype == 17 && model.type == 5)){
        //noting
    }else{
        if ([[YPJudgeNet shareJudgeNet] isConnection]) {
            NSString *url = [NSString stringWithFormat:@"http://pianke.me/webview/%@",model.contentid];
            YPWebViewVC *webVC = [[YPWebViewVC alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:webVC];
            webVC.tingID = url;
            webVC.type = @"动态";
            webVC.user = model.userinfo;
            webVC.like = model.counterList.like;
            webVC.shareImage = model.coverimg;
            webVC.shareTitle = model.title;
            [self.navigationController presentViewController:nav animated:YES completion:nil];
        }else{
            [self alertController:@"请先检查网络"];
        }
    }
}

- (void)alertController:(NSString*)str{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

+ (instancetype)shareDynamicVC{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dynamicVC = [[YPHomePageDynamicVC alloc]init];
    });
    return dynamicVC;
}
- (YPLikeHelper *)like{
    if (_like == nil) {
        _like = [[YPLikeHelper alloc]init];
    }
    return _like;
}

- (YPDataBase *)database{
    if (_database == nil) {
        _database = [[YPDataBase alloc]init];
    }
    return _database;
}
@end
